/**
 * 增强的邮件编辑器组件
 */
import React, { useState, useRef, useEffect } from 'react';
import {
  Card,
  Input,
  Button,
  Space,
  Tabs,
  Row,
  Col,
  Select,
  message,
  Tooltip,
  Divider,
} from 'antd';
import {
  CodeOutlined,
  EyeOutlined,
  ApiOutlined,
  TableOutlined,
  BranchesOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import VariableInserter from '../VariableInserter';
import {
  previewTemplate,
  type TemplatePreviewRequest,
  TemplateType,
} from '@/services/emailTemplate';
import {
  previewDataSourceData,
  type DataSourceDataPreview,
} from '@/services/dataSourceField';

const { TextArea } = Input;
const { TabPane } = Tabs;
const { Option } = Select;

interface EnhancedEmailEditorProps {
  value?: {
    subject: string;
    content: string;
  };
  onChange?: (value: { subject: string; content: string }) => void;
  dataSourceId?: number;
  templateType?: TemplateType;
  onPreview?: (previewData: any) => void;
}

const EnhancedEmailEditor: React.FC<EnhancedEmailEditorProps> = ({
  value = { subject: '', content: '' },
  onChange,
  dataSourceId,
  templateType = TemplateType.HTML,
  onPreview,
}) => {
  const [activeTab, setActiveTab] = useState('edit');
  const [variableInserterVisible, setVariableInserterVisible] = useState(false);
  const [previewLoading, setPreviewLoading] = useState(false);
  const [previewData, setPreviewData] = useState<any>(null);
  const [sampleData, setSampleData] = useState<DataSourceDataPreview | null>(null);
  const [insertTarget, setInsertTarget] = useState<'subject' | 'content'>('content');
  
  const subjectRef = useRef<any>(null);
  const contentRef = useRef<any>(null);

  // 获取样例数据
  const fetchSampleData = async () => {
    if (!dataSourceId) return;
    
    try {
      const preview = await previewDataSourceData(dataSourceId, 3);
      setSampleData(preview);
    } catch (error) {
      console.error('获取样例数据失败:', error);
    }
  };

  useEffect(() => {
    if (dataSourceId) {
      fetchSampleData();
    }
  }, [dataSourceId]);

  // 处理值变化
  const handleChange = (field: 'subject' | 'content', newValue: string) => {
    const newData = { ...value, [field]: newValue };
    onChange?.(newData);
  };

  // 插入变量
  const handleInsertVariable = (variable: string) => {
    if (insertTarget === 'subject') {
      const currentValue = value.subject;
      const input = subjectRef.current?.input;
      if (input) {
        const start = input.selectionStart || 0;
        const end = input.selectionEnd || 0;
        const newValue = currentValue.slice(0, start) + variable + currentValue.slice(end);
        handleChange('subject', newValue);
        
        // 设置光标位置
        setTimeout(() => {
          input.setSelectionRange(start + variable.length, start + variable.length);
          input.focus();
        }, 0);
      } else {
        handleChange('subject', currentValue + variable);
      }
    } else {
      const currentValue = value.content;
      const textarea = contentRef.current?.resizableTextArea?.textArea;
      if (textarea) {
        const start = textarea.selectionStart || 0;
        const end = textarea.selectionEnd || 0;
        const newValue = currentValue.slice(0, start) + variable + currentValue.slice(end);
        handleChange('content', newValue);
        
        // 设置光标位置
        setTimeout(() => {
          textarea.setSelectionRange(start + variable.length, start + variable.length);
          textarea.focus();
        }, 0);
      } else {
        handleChange('content', currentValue + variable);
      }
    }
    setVariableInserterVisible(false);
  };

  // 预览邮件
  const handlePreview = async () => {
    if (!value.subject || !value.content) {
      message.warning('请先填写邮件主题和内容');
      return;
    }

    setPreviewLoading(true);
    try {
      // 使用样例数据进行预览
      const variables = sampleData?.data?.[0] || {};
      
      const previewRequest: TemplatePreviewRequest = {
        subject: value.subject,
        content: value.content,
        template_type: templateType,
        variables,
      };

      const result = await previewTemplate(previewRequest);
      setPreviewData(result);
      setActiveTab('preview');
      onPreview?.(result);
      message.success('预览生成成功');
    } catch (error: any) {
      message.error(error.message || '预览生成失败');
    } finally {
      setPreviewLoading(false);
    }
  };

  // 插入表格模板
  const insertTableTemplate = () => {
    const tableTemplate = `
<table border="1" style="border-collapse: collapse; width: 100%;">
  <thead>
    <tr>
      <th>列1</th>
      <th>列2</th>
      <th>列3</th>
    </tr>
  </thead>
  <tbody>
    {% for row in data %}
    <tr>
      <td>{{row.column1}}</td>
      <td>{{row.column2}}</td>
      <td>{{row.column3}}</td>
    </tr>
    {% endfor %}
  </tbody>
</table>`;
    
    setInsertTarget('content');
    handleInsertVariable(tableTemplate);
  };

  // 插入条件模板
  const insertConditionalTemplate = () => {
    const conditionalTemplate = `
{% if condition %}
  <p>条件为真时显示的内容</p>
{% else %}
  <p>条件为假时显示的内容</p>
{% endif %}`;
    
    setInsertTarget('content');
    handleInsertVariable(conditionalTemplate);
  };

  // 插入循环模板
  const insertLoopTemplate = () => {
    const loopTemplate = `
<ul>
{% for item in items %}
  <li>{{item.name}}: {{item.value}}</li>
{% endfor %}
</ul>`;
    
    setInsertTarget('content');
    handleInsertVariable(loopTemplate);
  };

  return (
    <div>
      <Card>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="编辑邮件" key="edit">
            <Space direction="vertical" style={{ width: '100%' }} size="large">
              {/* 工具栏 */}
              <Row gutter={16}>
                <Col span={12}>
                  <Space wrap>
                    <Button
                      icon={<CodeOutlined />}
                      onClick={() => {
                        setInsertTarget('subject');
                        setVariableInserterVisible(true);
                      }}
                    >
                      主题插入变量
                    </Button>
                    <Button
                      icon={<CodeOutlined />}
                      onClick={() => {
                        setInsertTarget('content');
                        setVariableInserterVisible(true);
                      }}
                    >
                      内容插入变量
                    </Button>
                  </Space>
                </Col>
                <Col span={12} style={{ textAlign: 'right' }}>
                  <Space>
                    <Button
                      type="primary"
                      icon={<EyeOutlined />}
                      onClick={handlePreview}
                      loading={previewLoading}
                    >
                      预览邮件
                    </Button>
                  </Space>
                </Col>
              </Row>

              <Divider />

              {/* 快速插入工具 */}
              <Row gutter={16}>
                <Col span={24}>
                  <div style={{ marginBottom: 8 }}>
                    <strong>快速插入：</strong>
                  </div>
                  <Space wrap>
                    <Button
                      size="small"
                      icon={<TableOutlined />}
                      onClick={insertTableTemplate}
                    >
                      数据表格
                    </Button>
                    <Button
                      size="small"
                      icon={<BranchesOutlined />}
                      onClick={insertConditionalTemplate}
                    >
                      条件显示
                    </Button>
                    <Button
                      size="small"
                      icon={<PlusOutlined />}
                      onClick={insertLoopTemplate}
                    >
                      循环列表
                    </Button>
                  </Space>
                </Col>
              </Row>

              <Divider />

              {/* 邮件主题 */}
              <div>
                <div style={{ marginBottom: 8 }}>
                  <strong>邮件主题：</strong>
                </div>
                <Input
                  ref={subjectRef}
                  value={value.subject}
                  onChange={(e) => handleChange('subject', e.target.value)}
                  placeholder="请输入邮件主题，支持变量如：{{user_name}}"
                  size="large"
                />
              </div>

              {/* 邮件内容 */}
              <div>
                <div style={{ marginBottom: 8 }}>
                  <strong>邮件内容：</strong>
                </div>
                <TextArea
                  ref={contentRef}
                  value={value.content}
                  onChange={(e) => handleChange('content', e.target.value)}
                  placeholder="请输入邮件内容，支持HTML、变量和模板语法"
                  rows={15}
                  style={{ fontFamily: 'Monaco, Consolas, monospace' }}
                />
              </div>

              {/* 样例数据显示 */}
              {sampleData && sampleData.data.length > 0 && (
                <div>
                  <div style={{ marginBottom: 8 }}>
                    <strong>样例数据（用于预览）：</strong>
                  </div>
                  <div style={{ 
                    padding: 12, 
                    backgroundColor: '#f5f5f5', 
                    borderRadius: 4,
                    fontSize: 12,
                    fontFamily: 'Monaco, Consolas, monospace',
                  }}>
                    <pre>{JSON.stringify(sampleData.data[0], null, 2)}</pre>
                  </div>
                </div>
              )}
            </Space>
          </TabPane>

          <TabPane tab="预览效果" key="preview">
            {previewData ? (
              <div>
                <Card title="预览结果" style={{ marginBottom: 16 }}>
                  <div style={{ marginBottom: 16 }}>
                    <strong>渲染后的主题：</strong>
                    <div style={{ 
                      marginTop: 8, 
                      padding: 12, 
                      backgroundColor: '#f5f5f5',
                      borderRadius: 4,
                      fontSize: 16,
                      fontWeight: 500,
                    }}>
                      {previewData.rendered_subject}
                    </div>
                  </div>
                  
                  <div style={{ marginBottom: 16 }}>
                    <strong>HTML内容：</strong>
                    <div 
                      style={{ 
                        marginTop: 8, 
                        padding: 16, 
                        border: '1px solid #d9d9d9',
                        borderRadius: 4,
                        backgroundColor: '#fff',
                        minHeight: 300,
                      }}
                      dangerouslySetInnerHTML={{ __html: previewData.html_content }}
                    />
                  </div>

                  {previewData.variables_used && previewData.variables_used.length > 0 && (
                    <div style={{ marginBottom: 16 }}>
                      <strong>使用的变量：</strong>
                      <div style={{ marginTop: 8 }}>
                        <Space wrap>
                          {previewData.variables_used.map((variable: string, index: number) => (
                            <Tooltip key={index} title={`变量: ${variable}`}>
                              <span style={{ 
                                padding: '2px 6px',
                                backgroundColor: '#e6f7ff',
                                border: '1px solid #91d5ff',
                                borderRadius: 4,
                                fontSize: 12,
                                fontFamily: 'Monaco, Consolas, monospace',
                              }}>
                                {variable}
                              </span>
                            </Tooltip>
                          ))}
                        </Space>
                      </div>
                    </div>
                  )}

                  {previewData.missing_variables && previewData.missing_variables.length > 0 && (
                    <div>
                      <strong>缺失的变量：</strong>
                      <div style={{ marginTop: 8 }}>
                        <Space wrap>
                          {previewData.missing_variables.map((variable: string, index: number) => (
                            <Tooltip key={index} title={`缺失变量: ${variable}`}>
                              <span style={{ 
                                padding: '2px 6px',
                                backgroundColor: '#fff2f0',
                                border: '1px solid #ffccc7',
                                borderRadius: 4,
                                fontSize: 12,
                                fontFamily: 'Monaco, Consolas, monospace',
                                color: '#ff4d4f',
                              }}>
                                {variable}
                              </span>
                            </Tooltip>
                          ))}
                        </Space>
                      </div>
                    </div>
                  )}
                </Card>
              </div>
            ) : (
              <div style={{ textAlign: 'center', padding: 50, color: '#999' }}>
                请先在编辑页面点击"预览邮件"按钮生成预览
              </div>
            )}
          </TabPane>
        </Tabs>
      </Card>

      {/* 变量插入器 */}
      <VariableInserter
        visible={variableInserterVisible}
        onClose={() => setVariableInserterVisible(false)}
        onInsert={handleInsertVariable}
        currentDataSourceId={dataSourceId}
      />
    </div>
  );
};

export default EnhancedEmailEditor;
